{% extends 'base.html' %}
{% load static %}

{% block title %}地图找活动 - 本地有约{% endblock %}

{% block extra_css %}
<style>
    .map-page {
        height: calc(100vh - 80px);
        position: relative;
    }
    
    #map {
        width: 100%;
        height: 100%;
        border: 2px solid #e9ecef; /* 添加边框以便调试 */
    }
    
    .map-controls {
        position: absolute;
        top: 20px;
        left: 20px;
        z-index: 1000;
        background: white;
        padding: 15px;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        min-width: 300px;
        max-width: 350px;
    }
    
    .search-suggestions {
        position: absolute;
        background: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        max-height: 200px;
        overflow-y: auto;
        width: 100%;
        top: 100%;
        left: 0;
        margin-top: 2px;
        z-index: 1001;
        display: none;
    }
    
    .suggestion-item {
        padding: 10px;
        cursor: pointer;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .suggestion-item:hover {
        background-color: #f5f5f5;
    }
    
    .suggestion-item:last-child {
        border-bottom: none;
    }
    
    .activity-marker {
        cursor: pointer;
        text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
    }
    
    .activity-item {
        transition: all 0.3s ease;
        cursor: pointer;
    }
    
    .activity-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
    
    /* 加载状态样式 */
    .map-loading {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 1001;
        background: rgba(255,255,255,0.9);
        padding: 20px;
        border-radius: 10px;
        text-align: center;
    }
</style>
{% endblock %}

{% block content %}
<div class="map-page">
    <!-- 加载状态 -->
    <div id="mapLoading" class="map-loading" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2 mb-0">地图加载中...</p>
    </div>
    
    <div class="map-controls">
        <h5><i class="fas fa-map"></i> 地图找活动</h5>
        
        <!-- 位置信息显示 -->
        <div id="locationInfo" class="alert alert-info py-2 px-3 mb-3" style="display: none; font-size: 0.85rem;">
            <div><strong><i class="fas fa-map-marker-alt"></i> 当前位置</strong></div>
            <div id="currentAddress" class="text-muted small">--</div>
            <div id="currentCoords" class="text-muted small mt-1">
                <i class="fas fa-crosshairs"></i> 经度: <span id="coordLng">--</span> | 纬度: <span id="coordLat">--</span>
            </div>
        </div>
        
        <div class="mb-3 position-relative">
            <div class="input-group">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索地点、活动名称..." autocomplete="off">
                <button class="btn btn-outline-primary" type="button" id="searchButton">
                    <i class="fas fa-search"></i>
                </button>
            </div>
            <div id="searchSuggestions" class="search-suggestions"></div>
            <small class="text-muted">💡 可以输入城市、地点名称或活动标题</small>
        </div>
        <div class="mb-3">
            <label class="form-label">活动类型</label>
            <select class="form-select" id="activityTypeFilter">
                <option value="">所有类型</option>
            </select>
        </div>
        <div class="mb-3">
            <label class="form-label">搜索半径</label>
            <select class="form-select" id="radiusFilter">
                <option value="1000">1公里</option>
                <option value="3000" selected>3公里</option>
                <option value="5000">5公里</option>
                <option value="10000">10公里</option>
            </select>
        </div>
        <button class="btn btn-primary w-100 mb-3" id="searchNearbyBtn">
            <i class="fas fa-search"></i> 搜索附近活动
        </button>
        <button class="btn btn-outline-secondary w-100 mb-3" id="relocateBtn">
            <i class="fas fa-location-arrow"></i> 重新定位
        </button>
        <div id="nearbyResults" class="mt-3" style="max-height: 300px; overflow-y: auto;">
            <p class="text-muted text-center">点击"搜索附近活动"开始探索</p>
        </div>
    </div>
    <div id="map"></div>
</div>
{% endblock %}


{% block extra_js %}
<!-- 引入高德地图 JS API -->
<script src="https://webapi.amap.com/maps?v=2.0&key={{ amap_key }}"></script>
<script src="https://webapi.amap.com/ui/1.1/main.js"></script>    
<script>
    let map;
    let markers = [];
    let userLocation = null;
    let userMarker = null; // 用户位置标记
    let geocoder = null; // 地理编码服务
    let autoComplete = null; // 搜索提示

    // 初始化地图页面
    function initMapPage() {
        console.log('初始化地图...'); // 调试信息
        
        // 检查AMap对象是否加载
        if (typeof AMap === 'undefined') {
            console.error('高德地图API未正确加载');
            showError('地图加载失败，请刷新页面重试');
            return;
        }

        // 初始化地图
        map = new AMap.Map('map', {
            zoom: 13,
            center: [116.397428, 39.90923], // 北京中心
            resizeEnable: true,
            viewMode: '3D' // 使用3D视图
        });

        console.log('地图初始化完成'); // 调试信息

        // 添加比例尺控件（高德地图2.0）
        AMap.plugin(['AMap.Scale'], function() {
            const scale = new AMap.Scale({
                position: 'LB' // 左下角
            });
            map.addControl(scale);
            console.log('✅ 比例尺控件加载完成');
        });
        
        // 添加缩放控件（高德地图2.0）
        AMap.plugin(['AMap.ToolBar'], function() {
            const toolbar = new AMap.ToolBar({
                position: 'RB' // 右下角
            });
            map.addControl(toolbar);
            console.log('✅ 缩放控件加载完成');
        });
        
        // 添加鹰眼控件（可选）
        AMap.plugin(['AMap.HawkEye'], function() {
            const hawkEye = new AMap.HawkEye({
                opened: false,
                position: 'RT' // 右上角
            });
            map.addControl(hawkEye);
            console.log('✅ 鹰眼控件加载完成');
        });

        // 初始化地理编码服务和自动完成
        AMap.plugin(['AMap.Geocoder', 'AMap.AutoComplete'], function() {
            geocoder = new AMap.Geocoder({
                city: '全国',
                radius: 1000,
                extensions: 'all'
            });
            console.log('Geocoder 初始化完成');
            
            // 初始化自动完成
            autoComplete = new AMap.AutoComplete({
                city: '全国'
            });
            console.log('AutoComplete 初始化完成');
        });

        // 获取用户位置
        getCurrentLocation();

        // 加载活动类型
        loadActivityTypesForMap();

        // 搜索框事件
        const searchInput = document.getElementById('searchInput');
        const searchButton = document.getElementById('searchButton');
        const searchNearbyBtn = document.getElementById('searchNearbyBtn');
        const relocateBtn = document.getElementById('relocateBtn');
        
        // 搜索按钮点击事件
        if (searchButton) {
            searchButton.addEventListener('click', function() {
                console.log('🔍 搜索按钮被点击');
                const keyword = document.getElementById('searchInput').value.trim();
                console.log('搜索关键词:', keyword);
                searchLocation();
            });
        } else {
            console.error('❌ 搜索按钮元素未找到');
        }
        
        // 回车键搜索
        if (searchInput) {
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    console.log('⌨️ 回车键搜索');
                    const keyword = e.target.value.trim();
                    console.log('搜索关键词:', keyword);
                    searchLocation();
                }
            });
        } else {
            console.error('❌ 搜索输入框元素未找到');
        }
        
        // 搜索输入事件 - 显示建议
        searchInput.addEventListener('input', function(e) {
            const keyword = e.target.value.trim();
            if (keyword.length > 0) {
                showSearchSuggestions(keyword);
            } else {
                hideSearchSuggestions();
            }
        });
        
        // 搜索附近活动按钮
        searchNearbyBtn.addEventListener('click', function() {
            console.log('搜索附近活动按钮被点击');
            searchNearbyActivities();
        });
        
        // 重新定位按钮
        relocateBtn.addEventListener('click', function() {
            console.log('重新定位按钮被点击');
            getCurrentLocation();
        });
        
        // 点击地图时隐藏建议
        map.on('click', hideSearchSuggestions);
        
        // 搜索建议点击事件委托
        document.getElementById('searchSuggestions').addEventListener('click', function(e) {
            const suggestionItem = e.target.closest('.suggestion-item');
            if (suggestionItem) {
                const name = suggestionItem.getAttribute('data-name');
                const lng = parseFloat(suggestionItem.getAttribute('data-lng'));
                const lat = parseFloat(suggestionItem.getAttribute('data-lat'));
                selectSuggestion(name, lng, lat);
            }
        });
        
        // 添加点击事件监听器，用于调试
        map.on('click', function(e) {
            console.log('地图点击坐标:', e.lnglat.getLng(), e.lnglat.getLat());
        });
    }

    // 获取当前位置
    function getCurrentLocation() {
        showLoading('正在获取您的位置...');
        console.log('🌍 开始获取用户位置...');
        
        // 直接使用IP定位，速度更快，体验更好
        console.log('💡 使用IP定位，快速获取位置');
        useAmapIPLocation();
        
        // 注释掉浏览器定位，因为经常需要用户授权，体验不好
        // 如果需要精确定位，可以再添加一个"精确定位"按钮
        /*
        // 添加全局超时保护（6秒后强制使用IP定位）
        const globalTimeout = setTimeout(() => {
            console.warn('⚠️ 定位请求超时（6秒），使用IP定位');
            hideLoading();
            useAmapIPLocation();
        }, 6000);
        
        // 优先使用浏览器地理定位（最精确）
        if (navigator.geolocation) {
            console.log('📱 请求浏览器定位权限...');
            
            // 2秒后如果还在等待，提示用户并准备降级
            const permissionHintTimeout = setTimeout(() => {
                console.log('⏱️ 权限等待超过2秒，准备降级到IP定位');
            }, 2000);
            
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    clearTimeout(globalTimeout);
                    clearTimeout(permissionHintTimeout);
                    
                    console.log('✅ 浏览器定位成功！');
                    userLocation = {
                        lng: position.coords.longitude,
                        lat: position.coords.latitude
                    };
                    updateUserLocation('GPS定位');
                },
                function(error) {
                    clearTimeout(globalTimeout);
                    clearTimeout(permissionHintTimeout);
                    console.warn('⚠️ 浏览器定位失败:', error.message);
                    useAmapIPLocation();
                },
                {
                    enableHighAccuracy: false,
                    timeout: 3000,
                    maximumAge: 60000
                }
            );
        } else {
            clearTimeout(globalTimeout);
            useAmapIPLocation();
        }
        */
    }

    // 使用高德IP定位
    function useAmapIPLocation() {
        console.log('🌐 尝试使用IP定位...');
        
        // 添加5秒超时保护
        const ipTimeout = setTimeout(() => {
            console.warn('⚠️ IP定位超时（5秒），使用默认位置');
            hideLoading();
            useDefaultLocation();
        }, 5000);
        
        try {
            AMap.plugin('AMap.CitySearch', function() {
                const citySearch = new AMap.CitySearch();
                citySearch.getLocalCity(function(status, result) {
                    clearTimeout(ipTimeout);
                    
                    if (status === 'complete' && result.info === 'OK') {
                        console.log('✅ IP定位成功:', result);
                        console.log('- 城市:', result.city);
                        
                        if (result.rectangle) {
                            const bounds = result.rectangle.split(';');
                            const center1 = bounds[0].split(',');
                            const center2 = bounds[1].split(',');
                            userLocation = {
                                lng: (parseFloat(center1[0]) + parseFloat(center2[0])) / 2,
                                lat: (parseFloat(center1[1]) + parseFloat(center2[1])) / 2
                            };
                            console.log('- 经度:', userLocation.lng);
                            console.log('- 纬度:', userLocation.lat);
                            updateUserLocation('IP定位 - ' + result.city);
                        } else {
                            console.warn('⚠️ IP定位返回数据不完整');
                            useDefaultLocation();
                        }
                    } else {
                        console.warn('❌ IP定位失败:', status, result);
                        useDefaultLocation();
                    }
                });
            });
        } catch (error) {
            clearTimeout(ipTimeout);
            console.error('❌ IP定位异常:', error);
            hideLoading();
            useDefaultLocation();
        }
    }

    // 使用默认位置（北京天安门）
    function useDefaultLocation() {
        console.log('📍 使用默认位置（北京天安门）');
        userLocation = {
            lng: 116.397428,
            lat: 39.90923
        };
        console.log('- 经度:', userLocation.lng);
        console.log('- 纬度:', userLocation.lat);
        updateUserLocation('默认位置 - 北京');
    }

    // 更新用户位置到地图
    function updateUserLocation(source) {
        hideLoading();
        console.log('📍 更新用户位置:', userLocation, '来源:', source);
        
        // 更新经纬度显示
        updateLocationDisplay();
        
        // 移动地图中心到用户位置
        map.setCenter([userLocation.lng, userLocation.lat]);
        map.setZoom(15);
        
        // 移除旧的用户位置标记
        if (userMarker) {
            map.remove(userMarker);
        }
        
        // 添加蓝色的"我的位置"标记
        userMarker = new AMap.Marker({
            position: [userLocation.lng, userLocation.lat],
            map: map,
            icon: new AMap.Icon({
                size: new AMap.Size(30, 40),
                image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png', // 蓝色标记
                imageSize: new AMap.Size(30, 40)
            }),
            title: '我的位置',
            offset: new AMap.Pixel(-15, -40),
            zIndex: 999,
            animation: 'AMAP_ANIMATION_DROP' // 添加下落动画
        });
        
        // 获取详细地址
        if (geocoder) {
            geocoder.getAddress([userLocation.lng, userLocation.lat], function(status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    const address = result.regeocode.formattedAddress;
                    console.log('✅ 当前位置地址:', address);
                    showSuccess('📍 定位成功！当前位置: ' + address);
                    userMarker.setTitle('我的位置: ' + address);
                    
                    // 更新左侧面板显示
                    document.getElementById('currentAddress').textContent = address;
                    document.getElementById('locationInfo').style.display = 'block';
                } else {
                    console.warn('⚠️ 地址解析失败');
                    showSuccess('📍 定位成功！' + source);
                    document.getElementById('currentAddress').textContent = source;
                    document.getElementById('locationInfo').style.display = 'block';
                }
            });
        } else {
            showSuccess('📍 定位成功！' + source);
            document.getElementById('currentAddress').textContent = source;
            document.getElementById('locationInfo').style.display = 'block';
        }
        
        // 自动搜索附近活动
        console.log('🔍 自动搜索附近活动...');
        searchNearbyActivities();
    }
    
    // 更新位置信息显示
    function updateLocationDisplay(address) {
        const locationInfo = document.getElementById('locationInfo');
        const coordLng = document.getElementById('coordLng');
        const coordLat = document.getElementById('coordLat');
        
        if (userLocation) {
            locationInfo.style.display = 'block';
            coordLng.textContent = userLocation.lng.toFixed(6);
            coordLat.textContent = userLocation.lat.toFixed(6);
            
            if (address) {
                document.getElementById('currentAddress').textContent = address;
            }
        } else {
            locationInfo.style.display = 'none';
        }
    }

    // 搜索附近活动
    function searchNearbyActivities() {
        if (!userLocation) {
            console.warn('用户位置未获取');
            showError('无法获取当前位置，请先在搜索框输入地点或点击"重新定位"');
            return;
        }

        const radius = document.getElementById('radiusFilter').value;
        const activityType = document.getElementById('activityTypeFilter').value;

        let url = `/activities/api/nearby/?lat=${userLocation.lat}&lng=${userLocation.lng}&radius=${radius}`;
        if (activityType) {
            url += `&activity_type=${activityType}`;
        }

        console.log('搜索附近活动:', url); // 调试信息
        
        showLoading('搜索附近活动中...');

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常 (状态码: ' + response.status + ')');
                }
                return response.json();
            })
            .then(data => {
                hideLoading();
                console.log('搜索到活动:', data); // 调试信息
                if (data.error) {
                    showError(data.error);
                } else {
                    displayNearbyActivities(data.activities);
                    const count = data.activities ? data.activities.length : 0;
                    showSuccess(`找到 ${count} 个附近的活动`);
                }
            })
            .catch(error => {
                hideLoading();
                console.error('搜索附近活动失败:', error);
                showError('搜索失败: ' + error.message);
            });
    }

    // 显示附近活动
    function displayNearbyActivities(activities) {
        // 清除之前的标记
        clearMarkers();

        const resultsContainer = document.getElementById('nearbyResults');
        
        if (!activities || activities.length === 0) {
            resultsContainer.innerHTML = '<p class="text-muted">附近没有找到活动</p>';
            return;
        }

        // 显示结果列表
        resultsContainer.innerHTML = activities.map(activity => `
            <div class="card mb-2 activity-item" data-id="${activity.id}" 
                 onmouseenter="highlightMarker(${activity.id})" 
                 onmouseleave="unhighlightMarker(${activity.id})">
                <div class="card-body p-2">
                    <h6 class="card-title mb-1">${activity.title}</h6>
                    <p class="card-text text-muted mb-1">
                        <small><i class="fas fa-map-marker-alt"></i> ${activity.location_name}</small>
                    </p>
                    <p class="card-text mb-1">
                        <small><i class="fas fa-clock"></i> ${new Date(activity.start_time).toLocaleString('zh-CN')}</small>
                    </p>
                    <a href="/activities/${activity.id}/" class="btn btn-sm btn-primary">查看详情</a>
                </div>
            </div>
        `).join('');

        // 在地图上添加标记
        activities.forEach(activity => {
            const marker = new AMap.Marker({
                position: [activity.longitude, activity.latitude],
                map: map,
                title: activity.title,
                extData: { id: activity.id },
                content: `
                    <div class="activity-marker" data-id="${activity.id}">
                        <i class="fas fa-map-pin" style="color: #1890ff; font-size: 24px;"></i>
                    </div>
                `
            });

            // 信息窗口
            const infoWindow = new AMap.InfoWindow({
                content: `
                    <div class="p-2" style="min-width: 200px;">
                        <h6>${activity.title}</h6>
                        <p class="mb-1 text-muted">${activity.location_name}</p>
                        <p class="mb-2"><small>${new Date(activity.start_time).toLocaleString('zh-CN')}</small></p>
                        <a href="/activities/${activity.id}/" class="btn btn-sm btn-primary">查看详情</a>
                    </div>
                `,
                offset: new AMap.Pixel(0, -30)
            });

            marker.on('click', function() {
                infoWindow.open(map, marker.getPosition());
            });

            markers.push({
                marker: marker,
                id: activity.id
            });
        });

        // 调整地图视野包含所有标记
        if (activities.length > 0) {
            map.setFitView();
        }
    }

    // 高亮标记
    function highlightMarker(activityId) {
        const markerObj = markers.find(m => m.id === activityId);
        if (markerObj) {
            markerObj.marker.setAnimation('AMAP_ANIMATION_BOUNCE');
        }
    }

    // 取消高亮标记
    function unhighlightMarker(activityId) {
        const markerObj = markers.find(m => m.id === activityId);
        if (markerObj) {
            markerObj.marker.setAnimation(null);
        }
    }

    // 清除标记
    function clearMarkers() {
        markers.forEach(item => {
            map.remove(item.marker);
        });
        markers = [];
    }

    // 显示搜索建议
    function showSearchSuggestions(keyword) {
        if (!autoComplete) return;
        
        autoComplete.search(keyword, function(status, result) {
            if (status === 'complete' && result.tips) {
                const suggestions = document.getElementById('searchSuggestions');
                
                if (result.tips.length > 0) {
                    suggestions.innerHTML = result.tips
                        .filter(tip => tip.location) // 只显示有坐标的结果
                        .slice(0, 5) // 最多显示5条
                        .map(tip => `
                            <div class="suggestion-item" 
                                 data-name="${tip.name.replace(/"/g, '&quot;')}" 
                                 data-lng="${tip.location.lng}" 
                                 data-lat="${tip.location.lat}">
                                <i class="fas fa-map-marker-alt text-primary"></i>
                                <strong>${tip.name}</strong>
                                ${tip.district ? '<br><small class="text-muted">' + tip.district + '</small>' : ''}
                            </div>
                        `).join('');
                    suggestions.style.display = 'block';
                } else {
                    hideSearchSuggestions();
                }
            }
        });
    }
    
    // 隐藏搜索建议
    function hideSearchSuggestions() {
        const suggestions = document.getElementById('searchSuggestions');
        suggestions.style.display = 'none';
    }
    
    // 选择搜索建议
    function selectSuggestion(name, lng, lat) {
        console.log('📍 选择建议:', name, '坐标:', lng, lat);
        
        document.getElementById('searchInput').value = name;
        hideSearchSuggestions();
        
        // 更新用户位置
        userLocation = { lng: lng, lat: lat };
        
        // 判断是否是城市级别并设置缩放
        let zoomLevel = 15;
        if (name.includes('市') || name.includes('省') || name.includes('自治区')) {
            zoomLevel = 11; // 省市级别
        } else if (name.includes('区') || name.includes('县')) {
            zoomLevel = 13; // 区县级别
        }
        
        console.log('- 设置缩放级别:', zoomLevel);
        
        // 同时设置地图中心和缩放级别
        map.setZoomAndCenter(zoomLevel, [lng, lat]);
        
        // 更新用户标记
        if (userMarker) {
            map.remove(userMarker);
        }
        
        userMarker = new AMap.Marker({
            position: [lng, lat],
            map: map,
            icon: new AMap.Icon({
                size: new AMap.Size(30, 40),
                image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
                imageSize: new AMap.Size(30, 40)
            }),
            title: name,
            offset: new AMap.Pixel(-15, -40),
            zIndex: 999
        });
        
        console.log('✅ 地图已跳转到:', name);
        
        // 更新位置信息显示
        updateLocationDisplay(name);
        
        // 显示成功提示
        showSuccess('定位成功: ' + name);
        
        // 搜索附近活动
        searchNearbyActivities();
    }
    
    // 搜索地点或活动（优化版 - 快速搜索）
    function searchLocation() {
        const keyword = document.getElementById('searchInput').value.trim();
        if (!keyword) {
            showError('请输入搜索关键词');
            return;
        }

        console.log('🔍 开始快速搜索:', keyword);
        hideSearchSuggestions();
        showLoading('搜索中...');

        // 智能判断：如果是明显的地名，直接搜索地点（更快）
        const isLikelyPlace = isPlaceKeyword(keyword);
        
        if (isLikelyPlace) {
            console.log('💡 判断为地名，直接搜索地点');
            searchPlaceByName(keyword);
        } else {
            console.log('💡 可能是活动，尝试快速搜索');
            // 活动和地点并行搜索，哪个快用哪个（超时2秒）
            parallelSearch(keyword);
        }
    }
    
    // 判断是否为地名关键词
    function isPlaceKeyword(keyword) {
        // 常见地名特征
        const placePatterns = [
            /市$/, /省$/, /区$/, /县$/, /镇$/, /村$/,  // 行政区划
            /路$/, /街$/, /道$/, /巷$/, /弄$/,         // 道路
            /山$/, /河$/, /湖$/, /海$/, /岛$/,         // 地理
            /公园$/, /广场$/, /大厦$/, /中心$/,        // 建筑
            /站$/, /机场$/, /码头$/,                   // 交通
            /大学$/, /学院$/, /医院$/                  // 机构
        ];
        
        // 常见城市名
        const cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '重庆', 
                       '武汉', '西安', '天津', '苏州', '长沙', '郑州', '青岛', '厦门'];
        
        // 检查是否匹配地名模式
        for (const pattern of placePatterns) {
            if (pattern.test(keyword)) {
                return true;
            }
        }
        
        // 检查是否是常见城市
        for (const city of cities) {
            if (keyword.includes(city)) {
                return true;
            }
        }
        
        // 如果关键词很短（1-3个字）且不包含"活动"、"会议"等，可能是地名
        if (keyword.length <= 3 && !keyword.includes('活动') && !keyword.includes('会议')) {
            return true;
        }
        
        return false;
    }
    
    // 并行搜索（活动和地点同时搜索，快速响应）
    function parallelSearch(keyword) {
        let searchCompleted = false;
        
        // 设置2秒超时
        const timeout = new Promise((resolve) => {
            setTimeout(() => {
                if (!searchCompleted) {
                    console.log('⏱️ 搜索超时，直接搜索地点');
                    resolve({ type: 'timeout' });
                }
            }, 2000);
        });
        
        // 活动搜索
        const activitySearch = fetch(`/activities/api/list/?search=${encodeURIComponent(keyword)}`, {
            signal: AbortSignal.timeout(1500) // 1.5秒超时
        })
            .then(response => response.json())
            .then(data => {
                const activities = data.results || data;
                if (activities && activities.length > 0) {
                    return { type: 'activity', data: activities[0] };
                }
                return { type: 'none' };
            })
            .catch(error => {
                console.log('活动搜索失败或超时:', error.message);
                return { type: 'none' };
            });
        
        // 等待活动搜索或超时
        Promise.race([activitySearch, timeout])
            .then(result => {
                if (searchCompleted) return;
                
                if (result.type === 'activity') {
                    // 找到活动
                    searchCompleted = true;
                    hideLoading();
                    showActivityResult(result.data, keyword);
                } else {
                    // 没找到活动或超时，搜索地点
                    searchCompleted = true;
                    searchPlaceByName(keyword);
                }
            });
    }
    
    // 显示活动搜索结果
    function showActivityResult(activity, keyword) {
        console.log('✅ 找到活动:', activity.title);
        
        userLocation = {
            lng: parseFloat(activity.longitude),
            lat: parseFloat(activity.latitude)
        };
        
        // 快速跳转到活动位置
        map.setZoomAndCenter(16, [userLocation.lng, userLocation.lat]);
        
        // 添加红色标记
        if (userMarker) {
            map.remove(userMarker);
        }
        
        userMarker = new AMap.Marker({
            position: [userLocation.lng, userLocation.lat],
            map: map,
            icon: new AMap.Icon({
                size: new AMap.Size(30, 40),
                image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
                imageSize: new AMap.Size(30, 40)
            }),
            title: activity.title,
            offset: new AMap.Pixel(-15, -40),
            zIndex: 999
        });
        
        // 显示信息窗口
        const infoWindow = new AMap.InfoWindow({
            content: `
                <div class="p-2" style="min-width: 250px;">
                    <h6 class="mb-2"><i class="fas fa-calendar-alt text-primary"></i> ${activity.title}</h6>
                    <p class="mb-1"><i class="fas fa-map-marker-alt text-danger"></i> <strong>${activity.location_name}</strong></p>
                    <p class="mb-1 small text-muted">${activity.location_address}</p>
                    <div class="alert alert-info py-1 px-2 mb-2 small">
                        <strong>📍 坐标信息</strong><br>
                        经度: ${activity.longitude}<br>
                        纬度: ${activity.latitude}
                    </div>
                    <p class="mb-2 small"><i class="fas fa-clock"></i> ${new Date(activity.start_time).toLocaleString('zh-CN')}</p>
                    <a href="/activities/${activity.id}/" class="btn btn-sm btn-primary">查看详情</a>
                </div>
            `,
            offset: new AMap.Pixel(0, -30)
        });
        infoWindow.open(map, [userLocation.lng, userLocation.lat]);
        
        // 更新位置显示
        updateLocationDisplay(activity.location_name + ' - ' + activity.title);
        
        showSuccess(`✅ 找到活动: ${activity.title}`);
        
        // 搜索附近活动
        searchNearbyActivities();
    }
    
    // 根据活动名称搜索（保留用于其他地方调用）
    function searchActivityByName(keyword) {
        fetch(`/activities/api/list/?search=${encodeURIComponent(keyword)}`)
            .then(response => response.json())
            .then(data => {
                const activities = data.results || data;
                
                if (activities && activities.length > 0) {
                    hideLoading();
                    showActivityResult(activities[0], keyword);
                } else {
                    // 没找到活动，尝试地点搜索
                    searchPlaceByName(keyword);
                }
            })
            .catch(error => {
                console.warn('活动搜索失败，尝试地点搜索:', error);
                searchPlaceByName(keyword);
            });
    }
    
    // 根据地点名称搜索（优化版 - 快速响应）
    function searchPlaceByName(keyword) {
        console.log('🌍 地点搜索:', keyword);
        
        // 使用地理编码搜索
        if (!geocoder) {
            console.error('❌ Geocoder 未初始化，尝试重新初始化...');
            
            // 尝试重新初始化
            AMap.plugin(['AMap.Geocoder'], function() {
                geocoder = new AMap.Geocoder({
                    city: '全国',
                    radius: 1000,
                    extensions: 'all'
                });
                console.log('✅ Geocoder 重新初始化成功');
                searchPlaceByName(keyword);
            });
            return;
        }
        
        // 使用高德地图地理编码API（快速模式）
        geocoder.getLocation(keyword, function(status, result) {
            hideLoading();
            
            if (status === 'complete' && result.info === 'OK' && result.geocodes && result.geocodes.length > 0) {
                const geocode = result.geocodes[0];
                const location = geocode.location; // AMap.LngLat对象
                const address = geocode.formattedAddress || keyword;
            
                userLocation = {
                    lng: location.getLng(),
                    lat: location.getLat()
                };
            
                console.log('✅ 地点搜索成功:', keyword, `(${userLocation.lng.toFixed(4)}, ${userLocation.lat.toFixed(4)})`);
                
                // 快速判断缩放级别
                const level = geocode.level;
                let zoomLevel = (level === 'city' || level === 'province') ? 11 : 
                               (level === 'district') ? 13 : 15;
                
                // 快速跳转
                map.setZoomAndCenter(zoomLevel, [userLocation.lng, userLocation.lat]);
                
                // 添加红色标记
                if (userMarker) {
                    map.remove(userMarker);
                }
                
                userMarker = new AMap.Marker({
                    position: [userLocation.lng, userLocation.lat],
                    map: map,
                    icon: new AMap.Icon({
                        size: new AMap.Size(30, 40),
                        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 红色标记
                        imageSize: new AMap.Size(30, 40)
                    }),
                    title: address,
                    offset: new AMap.Pixel(-15, -40),
                    zIndex: 999
                });
                
                // 快速显示信息窗口
                const infoWindow = new AMap.InfoWindow({
                    content: `
                        <div class="p-2" style="min-width: 200px;">
                            <h6 class="mb-2"><i class="fas fa-map-marker-alt text-danger"></i> ${keyword}</h6>
                            <p class="mb-1 small text-muted">${address}</p>
                            <div class="alert alert-success py-1 px-2 mb-0 small">
                                <strong>📍 坐标</strong><br>
                                ${userLocation.lng.toFixed(6)}, ${userLocation.lat.toFixed(6)}
                            </div>
                        </div>
                    `,
                    offset: new AMap.Pixel(0, -30)
                });
                infoWindow.open(map, [userLocation.lng, userLocation.lat]);
                
                // 更新显示
                updateLocationDisplay(address);
                showSuccess('✅ 定位成功: ' + keyword);
                
                // 搜索附近活动
                searchNearbyActivities();
            } else {
                console.warn('未找到:', keyword);
                showError('❌ 未找到 "' + keyword + '"');
            }
        });
    }
    
    // 加载活动类型到地图页面
    function loadActivityTypesForMap() {
        fetch('/activities/api/types/')
            .then(response => response.json())
            .then(data => {
                console.log('活动类型API返回:', data);
                
                // 处理不同的返回格式
                let types;
                if (data.data && data.data.results) {
                    // 格式: {code: 200, data: {results: [...]}}
                    types = data.data.results;
                } else if (data.results) {
                    // 格式: {results: [...]}
                    types = data.results;
                } else if (Array.isArray(data)) {
                    // 格式: [...]
                    types = data;
                } else {
                    console.error('未知的API返回格式:', data);
                    return;
                }
                
                const select = document.getElementById('activityTypeFilter');
                if (!select) {
                    console.warn('未找到活动类型选择框');
                    return;
                }
                
                if (!Array.isArray(types)) {
                    console.error('types不是数组:', types);
                    return;
                }
                
                types.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type.id;
                    option.textContent = type.name;
                    select.appendChild(option);
                });
                
                console.log(`✅ 已加载 ${types.length} 个活动类型`);
            })
            .catch(error => {
                console.error('加载活动类型失败:', error);
            });
    }

    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initMap);
    } else {
        initMap();
    }
    
    function initMap() {
        console.log('DOM加载完成，准备初始化地图');
        
        // 等待高德地图API加载完成
        let attempts = 0;
        const maxAttempts = 20;
        const checkAMap = setInterval(() => {
            attempts++;
            if (typeof AMap !== 'undefined') {
                clearInterval(checkAMap);
                console.log('高德地图API加载成功');
                initMapPage();
            } else if (attempts >= maxAttempts) {
                clearInterval(checkAMap);
                console.error('高德地图API加载超时');
                showError('地图加载失败，请刷新页面重试');
            }
        }, 100);
    }
    
    // 辅助函数
    function showLoading(message = '加载中...') {
        const loadingEl = document.getElementById('mapLoading');
        if (loadingEl) {
            loadingEl.querySelector('p').textContent = message;
            loadingEl.style.display = 'block';
        }
    }
    
    function hideLoading() {
        const loadingEl = document.getElementById('mapLoading');
        if (loadingEl) {
            loadingEl.style.display = 'none';
        }
    }
    
    function showSuccess(message) {
        // 使用Bootstrap Toast或简单的alert
        if (typeof bootstrap !== 'undefined' && bootstrap.Toast) {
            // 创建Toast元素
            const toastHtml = `
                <div class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="fas fa-check-circle me-2"></i>${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            `;
            
            // 添加到页面
            let toastContainer = document.querySelector('.toast-container');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
                document.body.appendChild(toastContainer);
            }
            
            const toastEl = document.createElement('div');
            toastEl.innerHTML = toastHtml;
            toastContainer.appendChild(toastEl.firstElementChild);
            
            const toast = new bootstrap.Toast(toastEl.firstElementChild, { delay: 3000 });
            toast.show();
            
            // 自动移除
            toastEl.firstElementChild.addEventListener('hidden.bs.toast', function() {
                this.remove();
            });
        } else {
            console.log('Success:', message);
            alert(message);
        }
    }
    
    function showError(message) {
        // 使用Bootstrap Toast或简单的alert
        if (typeof bootstrap !== 'undefined' && bootstrap.Toast) {
            const toastHtml = `
                <div class="toast align-items-center text-white bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="fas fa-exclamation-circle me-2"></i>${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            `;
            
            let toastContainer = document.querySelector('.toast-container');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
                document.body.appendChild(toastContainer);
            }
            
            const toastEl = document.createElement('div');
            toastEl.innerHTML = toastHtml;
            toastContainer.appendChild(toastEl.firstElementChild);
            
            const toast = new bootstrap.Toast(toastEl.firstElementChild, { delay: 5000 });
            toast.show();
            
            toastEl.firstElementChild.addEventListener('hidden.bs.toast', function() {
                this.remove();
            });
        } else {
            console.error('Error:', message);
            alert(message);
        }
    }
</script>
{% endblock %}